/*
 * Copyright 2010-2012 Susanta Tewari. <freecode4susant@users.sourceforge.net>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * This file incorporates work covered by the following copyright and
 * permission notice:
 *
 * Copyright 2012 Boni Gopalan [https://code.google.com/p/whiteboardjunkie/] http://www.entelligentsia.in/blog/2012/01/26/folderlistener-for-jdk7-watch-folder-events-more-elegantly/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package commons.util.filewatch;

import java.io.IOException;
import java.nio.file.*;
import java.util.concurrent.*;

public class FolderWatchers {

    private static FolderWatchers watchers        = null;
    private static WatchService watchService      = null;
    private static final ExecutorService executor = Executors.newCachedThreadPool();

    private FolderWatchers() {

        try {
            watchService = FileSystems.getDefault().newWatchService();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static FolderWatchers getInstance() {

        if (null == watchers) watchers = new FolderWatchers();

        return watchers;
    }

    public FolderWatcherFuture addFolderListener(Path path, ChangeListener changeListener)
            throws IOException {

        FolderWatcher aWatcher     = new FolderWatcher(path, changeListener, watchService);
        Future f                   = executor.submit(aWatcher);
        FolderWatcherFuture future = new FolderWatcherFuture(aWatcher, f);

        return future;
    }

    public void cancelFolderWatching(FolderWatcherFuture folderWatcherFuture) {}
}

class FolderWatcher implements Runnable {

    private WatchKey watchKey       = null;
    private ChangeListener listener = null;

    protected FolderWatcher(Path path, ChangeListener changeListener, WatchService watchService)
            throws IOException {

        watchKey = path.register(watchService, changeListener.getEventTypes());
        listener = changeListener;
    }

    @Override
    public void run() {

        while (!cancel) {

            for (WatchEvent anEvent : watchKey.pollEvents()) {
                listener.onEvent((WatchEvent<Path>) anEvent);
            }
        }
    }

    private boolean cancel = false;

    protected void cancel() {
        this.cancel = true;
    }
}

class FolderWatcherFuture implements Future {

    private FolderWatcher watcher = null;
    private Future future         = null;

    public FolderWatcherFuture(FolderWatcher watcher, Future future) {

        this.watcher = watcher;
        this.future  = future;
    }

    @Override
    public boolean cancel(boolean mayInterruptIfRunning) {

        watcher.cancel();

        return future.cancel(mayInterruptIfRunning);
    }

    @Override
    public Object get() throws InterruptedException, ExecutionException {
        return future.get();
    }

    @Override
    public Object get(long timeout, TimeUnit unit)
            throws InterruptedException, ExecutionException, TimeoutException {
        return future.get(timeout, unit);
    }

    @Override
    public boolean isCancelled() {
        return future.isCancelled();
    }

    @Override
    public boolean isDone() {
        return future.isDone();
    }
}
